package org.scribe.extractors;

import org.scribe.model.Token;
import org.scribe.utils.Preconditions;
import org.scribe.utils.URLUtils;

import java.util.Enumeration;
import java.util.Hashtable;

/**
 * Default implementation of {@RequestTokenExtractor} and {@AccessTokenExtractor}. Conforms to OAuth 1.0a
 * <p/>
 * The process for extracting access and request tokens is similar so this class can do both things.
 *
 * @author Pablo Fernandez
 */
public class TokenExtractorImpl implements RequestTokenExtractor, AccessTokenExtractor {
    private static final String TOKEN_REGEX = "oauth_token=(\\S*)&oauth_token_secret=(\\S*?)(&(.*))?";

    /**
     * {@inheritDoc}
     */
    public Token extract(String response) {
//        Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");
//
//        Matcher matcher = Pattern.compile(TOKEN_REGEX).matcher(response);
//        if (matcher.matches()) {
//            String token = URLUtils.percentDecode(matcher.group(1));
//            String secret = URLUtils.percentDecode(matcher.group(2));
//
//            return new Token(token, secret);
//        } else {
//            throw new OAuthException("Response body is incorrect. Can't extract a token from this: '" + response + "'", null);
//        }
        Token ret = null;
        Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");

        String[] strs = response.split("&");
        if (strs != null) {
            int len = strs.length;
            int index;
            String str;
            String n, v;
            String token, secret;
            Hashtable<String, String> hs = new Hashtable<String, String>();
            for (int i = 0; i < len; i++) {
                str = strs[i];
                index = str.indexOf('=');
                if (index != -1) {
                    n = URLUtils.percentDecode(str.substring(0, index).trim());
                    v = URLUtils.percentDecode(str.substring(index + 1).trim());
                    hs.put(n, v);
                }
            }
            token = hs.get("oauth_token");
            secret = hs.get("oauth_token_secret");
            ret = new Token(token, secret);
            Enumeration<String> ks = hs.keys();
            while (ks.hasMoreElements()) {
                String kn = ks.nextElement();
                if (!kn.equals("oauth_token") && !kn.equals("oauth_token_secret")) {
                    ret.addOther(kn, hs.get(kn));
                }
            }
        }

        return ret;
    }
}
